<!--
 * @Author: zqx me_zqx@163.com
 * @Date: 2025-02-21 10:05:29
 * @LastEditors: zqx me_zqx@163.com
 * @LastEditTime: 2025-09-01 18:19:11
 * @FilePath: /XMate-h5/src/views/myXmate/components/scoreTable.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="bg-white">
    <!-- 头部 -->
    <div class="flex flex-row justify-between items-center p-4">
      <div class="flex flex-row items-center gap-2">
        <template v-for="(tab, idx) in tabList" :key="idx">
          <div class="flex flex-row items-center gap-2">
            <p
              @click="index = idx"
              :class="{
                'text-yxt-blue': index === idx,
                'cursor-pointer': true,
                'text-sm': true,
              }"
            >
              {{ tab.name }}
            </p>
            <div
              v-if="idx < tabList.length - 1 && isTeam"
              class="w-[1px] h-[16px] bg-[#999999]"
            ></div>
          </div>
        </template>
      </div>

      <p class="text-[#8C8C8C] text-xs">红字代表低于直属团队均值</p>
      <div
        class="flex flex-row items-center gap-1"
        v-if="showFilter"
        @click="handleFilter"
      >
        <p class="text-[#262626] text-sm">
          {{
            selectedMemberList.length > 0
              ? `部分销售(${selectedMemberList.length})`
              : "全部销售"
          }}
        </p>
        <van-icon name="arrow-down" color="#262626" />
      </div>
    </div>

    <div class="overflow-y-auto">
      <el-table :data="currentTableData" :border="false" stripe>
        <el-table-column
          v-for="item in currentColumns"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :fixed="item.fixed"
          :width="item.width"
          :sortable="(item.isSocre ? true : false) && enableSort"
        >
          <template #default="scope" v-if="item.customRender">
            <span
              :class="{
                'text-red-500':
                  item.isSocre && Number(scope.row[item.prop]) < item.average,
              }"
            >
              {{ item.formatter ? item.formatter(scope.row) : scope.row[item.prop] }}
            </span>
          </template>
          <template #default="scope" v-else-if="item.formatter">
            {{ item.formatter(scope.row) }}
          </template>
        </el-table-column>
      </el-table>
    </div>

    <van-action-sheet v-model:show="showChoosePeople" title="销售筛选">
      <div class="h-[680px]">
        <ChoosePeopleView
          v-if="showChoosePeople"
          @confirm="onConfirmPeople"
          :defaultTeamId="teamId"
          :defaultSelectedItems="selectedMemberList"
        />
      </div>
    </van-action-sheet>
  </div>
</template>

<script setup>
import { ref, defineProps, computed, defineEmits, inject } from "vue";
import ChoosePeopleView from "@/components/choosePeople/choosePeopleView.vue";
import { formatValue } from "@/utils/num";
import { useCommonStore } from "@/store";

const commonStore = useCommonStore();

// 是否存在商机
const enableBusinessOpportunity = computed(() => commonStore.enableBusinessOpportunity);

const index = ref(0);
const emits = defineEmits(["onFilterPeople"]);
const teamId = inject("teamNoticeBoard/teamId");

const props = defineProps({
  memberBoardList: {
    type: Array,
    default: () => [],
  },
  teamBoardList: {
    type: Array,
    default: () => [],
  },
  isTeam: {
    type: Boolean,
    default: false,
  },
  enableFilter: {
    type: Boolean,
    default: true,
  },
  enableSort: {
    type: Boolean,
    default: true,
  },
  selectedMemberList: {
    type: Array,
    default: () => [],
  },
  memberId: {
    type: String,
    default: null,
  },
});

const showChoosePeople = ref(false);

function handleFilter() {
  console.log("handleFilter");
  showChoosePeople.value = true;
}

function onConfirmPeople(memberList) {
  // [{id,name}]
  console.log("onConfirmPeople", memberList);
  showChoosePeople.value = false;
  emits("onFilterPeople", memberList);
}

// 添加计算平均分的函数
const calculateAverage = (list, prop) => {
  if (!list || list.length === 0) return 0;
  const sum = list.reduce((acc, curr) => acc + (Number(curr[prop]) || 0), 0);
  return sum / list.length;
};

// 修改 memberTableData 中的表格列配置
const memberTableData = computed(() => {
  let arr = [];
  // 基础信息列
  arr.push({
    label: "姓名",
    prop: "userName",
    isSocre: false,
    fixed: true,
  });
  arr.push({ label: "账号", prop: "userAccount", isSocre: false });
  arr.push({ label: "部门", prop: "deptName", isSocre: false });

  // 沟通计划相关列
  arr.push({
    label: "沟通计划总数",
    prop: "totalVisitPlanCount",
    isSocre: true,
  });

  // arr.push({
  //   label: "沟通计划完成率",
  //   prop: "visitPlanCompletionRate",
  //   isSocre: true,
  //   formatter: (row) => `${formatValue(row.visitPlanCompletionRate, 0, true)}%`,
  // });

  arr.push({
    label: "沟通计划覆盖客户数",
    prop: "visitPlanCustomerCount",
    isSocre: true,
  });
  enableBusinessOpportunity.value &&
    arr.push({
      label: "沟通计划覆盖商机数",
      prop: "visitPlanOpportunityCount",
      isSocre: true,
    });

  // 沟通执行相关列
  arr.push({ label: "沟通总次数", prop: "totalVisitCount", isSocre: true });
  arr.push({
    label: "沟通覆盖客户数",
    prop: "visitedCustomerCount",
    isSocre: true,
  });

  enableBusinessOpportunity.value &&
    arr.push({
      label: "沟通覆盖商机数",
      prop: "visitedOpportunityCount",
      isSocre: true,
    });

  // arr.push({
  //   label: "沟通目标达成率",
  //   prop: "visitTargetAchievementRate",
  //   isSocre: true,
  //   formatter: (row) => `${formatValue(row.visitTargetAchievementRate, 0, true)}%`,
  // });

  arr.push({
    label: "能力评估达标率",
    prop: "salesAbilityPassRate",
    isSocre: true,
    formatter: (row) => `${formatValue(row.salesAbilityPassRate, 0, true)}%`,
  });

  arr.push({
    label: "任务达成达标率",
    prop: "taskCompletePassRate",
    isSocre: true,
    formatter: (row) => `${formatValue(row.taskCompletePassRate, 0, true)}%`,
  });

  // 为每个 isSocre 为 true 的列添加自定义渲染
  return arr.map((column) => {
    if (column.isSocre) {
      const average = calculateAverage(props.memberBoardList, column.prop);
      return {
        ...column,
        // 添加自定义渲染
        customRender: true,
        width: column.label.length * 10 + 90,
        average,
        formatter: (row) => {
          const value = row[column.prop];
          // 保持原有的格式化逻辑
          if (column.formatter) {
            return column.formatter(row);
          }
          return value;
        },
      };
    }
    return column;
  });
});

// 新增 teamTableData 计算属性
const teamTableData = computed(() => {
  let arr = [];

  // 基础信息
  arr.push({
    label: "部门",
    prop: "deptName",
    fixed: true,
  });

  // 沟通计划相关
  arr.push({
    label: "沟通计划总数",
    prop: "totalVisitPlanCount",
    isSocre: true,
  });
  // arr.push({
  //   label: "沟通计划完成率",
  //   prop: "visitPlanCompletionRate",
  //   isSocre: true,
  //   formatter: (row) => `${formatValue(row.visitPlanCompletionRate, 0, true)}%`,
  // });
  arr.push({
    label: "沟通计划覆盖客户数",
    isSocre: true,
    prop: "visitPlanCustomerCount",
  });
  arr.push({
    label: "人均沟通计划数",
    isSocre: true,
    prop: "averageVisitPlanPerPerson",
    formatter: (row) => row.averageVisitPlanPerPerson.toFixed(0),
  });

  // 沟通执行相关
  arr.push({
    label: "沟通总次数",
    isSocre: true,
    prop: "totalVisitCount",
  });
  arr.push({
    label: "沟通覆盖客户数",
    isSocre: true,
    prop: "visitedCustomerCount",
  });
  arr.push({
    label: "人均沟通次数",
    isSocre: true,
    prop: "averageVisitsPerPerson",
    formatter: (row) => row.averageVisitsPerPerson.toFixed(0),
  });
  arr.push({
    label: "沟通目标达成率",
    isSocre: true,
    prop: "visitTargetAchievementRate",
    formatter: (row) => `${formatValue(row.visitTargetAchievementRate, 0, true)}%`,
  });

  // 评估相关
  arr.push({
    label: "能力评估达标率",
    prop: "salesAbilityPassRate",
    isSocre: true,
    formatter: (row) => `${formatValue(row.salesAbilityPassRate, 0, true)}%`,
  });
  arr.push({
    label: "任务完成达标率",
    prop: "taskStandardScore",
    isSocre: true,
    formatter: (row) => `${formatValue(row.taskCompletePassRate, 0, true)}%`,
  });

  arr.map((item) => {
    item.width = item.label.length * 10 + 90;
  });

  return arr;
});

// 定义标签列表
const tabList = computed(() => {
  let arr = [];
  if (props.isTeam) {
    arr.push({ name: "团队", type: "team" });
  }
  arr.push({ name: "成员", type: "member" });
  return arr;
});

const currentTab = computed(() => {
  if (index.value >= tabList.value.length) {
    return tabList.value[0];
  }
  return tabList.value[index.value];
});

// 根据当前选中的标签返回对应的数据
const currentTableData = computed(() => {
  let data = isSelectedMember.value ? props.memberBoardList : props.teamBoardList;
  console.log("currentTableData", data);
  return data;
});

// 是否选中成员tab
const isSelectedMember = computed(() => {
  return currentTab.value.type === "member";
});

const showFilter = computed(() => {
  return props.enableFilter && isSelectedMember.value;
});

// 根据当前选中的标签返回对应的列配置
const currentColumns = computed(() => {
  return currentTab.value.type === "team" ? teamTableData.value : memberTableData.value;
});
</script>

<style lang="less" scoped>
:deep(.el-table) {
  --el-table-border-color: transparent;
  --el-table-header-bg-color: #f5f5f5;

  // 移除单元格边框
  // 移除单元格边框
  .el-table__cell {
    border: none !important;
    // max-width: 100px; // 设置最大宽度
  }

  // 保持底部边框
  .el-table__row {
    border-bottom: 1px solid #e5e5e5;
  }

  // 表头不换行，超出显示省略号
  .el-table__header-wrapper {
    th {
      .cell {
        max-width: 190px;
      }
    }
  }

  // 内容超出时换行显示
  .el-table__body-wrapper {
    td {
      .cell {
        white-space: normal;
        word-break: break-all;
      }
    }
  }

  // 添加排序图标样式
  .caret-wrapper {
    height: 20px;

    .sort-caret {
      border-width: 4px;
    }
  }

  .ascending .sort-caret.ascending {
    border-bottom-color: #0fad72;
  }

  .descending .sort-caret.descending {
    border-top-color: #0fad72;
  }
}

// 确保表格内容可以横向滚动
.overflow-x-auto {
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

::-webkit-scrollbar {
  display: none;
  /* 对于 Chrome, Safari 和 Opera */
}

body {
  overflow: hidden;
  /* 隐藏整个页面的滚动条 */
}

/* 对于 Firefox */
html {
  scrollbar-width: none;
  /* 隐藏滚动条 */
}
</style>
